<template>
  <div class="common_wrap">
    <div class="common_title">辖区指标管理</div>
    <el-form
      ref="queryForm"
      :model="queryParams"
      label-width="75px"
      inline
      class="search-nav"
    >
      <el-form-item prop="area" label="区域选择">
        <el-select v-model="queryParams.area" filterable clearable>
          <el-option
            v-for="(item, index) in areaList"
            :key="item.value + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="date" label="期号">
        <el-select v-model="queryParams.date" clearable>
          <el-option
            v-for="(item, index) in dateList"
            :key="item.value + index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item prop="indicator" label="指标查询">
        <el-input
          v-model="queryParams.indicator"
          maxlength="20"
          placeholder="请输入指标名称"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >查询</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="btn-container" style="text-align: right; margin-bottom: 15px">
      <el-button
        type="primary"
        icon="el-icon-warning-outline"
        @click="checkError"
        >最新异常数据</el-button
      >
      <!-- <el-button type="primary" icon="el-icon-plus" @click="toImport" disabled >指标数据录入</el-button> -->
      <el-button type="primary" icon="el-icon-download" @click="exportHandel"
        >下载模板</el-button
      >
      <el-button type="primary" icon="el-icon-upload2" @click="importHandel"
        >指标数据导入</el-button
      >
    </div>
    <el-table ref="table" v-loading="tableLoading" :data="tableData">
      <el-table-column prop="issueNo" label="期号" align="center" width="100" />
      <el-table-column prop="areaName" label="区域" align="center" />
      <el-table-column
        prop="empName"
        label="责任领导"
        align="center"
        width="100"
      />
      <el-table-column prop="quotaName" label="指标名称" align="center" />
      <el-table-column prop="position" label="位次" align="center" width="60" />
      <el-table-column prop="signage" label="赋牌" align="center" width="60">
        <template slot-scope="scope">
          <span :class="formateColor(scope.row.signage)">{{
            formateCard(scope.row.signage)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="dimensionList"
        label="指标维度"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-for="item in scope.row.dimensionDTOList" :key="item.index"
            >{{ item.dimension + ": " + item.unitValue + item.unit + "  " }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button
              type="primary"
              :circle="true"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination-container"
      :background="true"
      :current-page="queryParams.current"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="queryParams.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <importFile
      ref="importFile"
      :upload-api="uploadApi"
      @onSuccess="onSuccess"
    />
    <el-dialog :visible.sync="visible" title="辖区指标信息编辑" width="800px">
      <el-form class="edit_box">
        <div class="date flex">
          <div>期号：</div>
          <div>{{ currentRow.issueNo }}</div>
        </div>
        <div class="quota_info flex">
          <div class="left flex">
            <div>指标ID：</div>
            <div>{{ currentRow.quotaId }}</div>
          </div>
          <div class="right flex">
            <div>指标名称：</div>
            <div>{{ currentRow.quotaName }}</div>
          </div>
        </div>
        <div class="quota_info flex">
          <div class="left flex">
            <div>区域：</div>
            <div>{{ currentRow.areaName }}</div>
          </div>
          <div class="right flex">
            <div>负责领导：</div>
            <div>{{ currentRow.empName }}</div>
          </div>
        </div>
        <div class="inx_box flex">
          <div class="left flex">
            <div class="tit">位次：</div>
            <div class="old">{{ currentRow.position }}</div>
            <div class="change">修改位次</div>
            <div class="input_box">
              <el-input
                v-model="form.inx"
                maxlength="3"
                size="mini"
                style="width: 100px"
                placeholder="位次"
                type="number"
              />
            </div>
          </div>
          <div class="right flex">
            <div class="tit">赋牌：</div>
            <div class="card" :class="formateColor(currentRow.signage)">
              {{ formateCard(currentRow.signage) }}
            </div>
            <div class="change">修改赋牌</div>
            <div class="input_box">
              <el-select
                v-model="form.signage"
                placeholder="请选择"
                size="mini"
                style="width: 80px"
              >
                <el-option
                  v-for="(item, i) in signageList"
                  :key="i"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </div>
          </div>
        </div>
        <div class="dgree_box flex">
          <div class="tit">维度：</div>
          <div class="content">
            <div
              class="item flex"
              v-for="quota in form.dimensionDTOList"
              :key="quota.index"
            >
              <div class="tit">{{ quota.dimension }}：</div>
              <div class="input_box">
                <el-input
                  v-model="quota.unitValue"
                  maxlength="4"
                  size="mini"
                  placeholder="请输入任务数"
                  type="number"
                />
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="importVisible"
      title="指标数据导入"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="importForm"
        :model="$data"
        label-width="80px"
        class="search-nav"
      >
        <el-form-item prop="issueNo" label="导入期号" class="is-required">
          <el-input
            v-model="importIssueNo"
            placeholder="请输入导入期号，如：2022-8"
          ></el-input>
        </el-form-item>
        <el-form-item prop="file" label="指标数据" class="is-required">
          <el-upload
            ref="upload"
            class="upload-demo"
            :headers="headers"
            :action="actionUrl"
            :limit="1"
            :on-success="successUp"
            :on-remove="deleteFile"
            :before-upload="beforeUpload"
            :data="uploadData"
            :auto-upload="false"
          >
            <el-button ref="files" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              支持文件格式：.xls、.xlsx。
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeImport">取 消</el-button>
        <el-button type="primary" @click="confirmImport">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="uploadVisible"
      title="导入指标信息"
      width="30%"
      :close-on-click-modal="false"
    >
      <div>{{ uploadMessage }}</div>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: space-between"
      >
        <div>
          <el-button type="primary" @click="checkError" v-if="isError"
            >查看异常数据</el-button
          >
        </div>
        <div>
          <el-button @click="uploadVisible = false">取 消</el-button>
          <el-button type="primary" @click="uploadVisible = false"
            >确 定</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import importFile from "@/components/importFile";
export default {
  name: "KeyIndicators",
  components: {
    importFile,
  },
  data() {
    return {
      areaList: [],
      dateList: [],
      // 搜索条件
      queryParams: {
        area: "",
        date: "",
        indicator: "",
        current: 1, // 第几页
        size: 10, // 每页条数
      },
      total: 0, // 总条数
      tableLoading: false, // 表格loading
      tableData: [], // 表格数据
      uploadApi: "/quotaFile/insertBatch",
      currentRow: {},
      visible: false,
      importVisible: false,
      signageList: [
        {
          label: "绿",
          value: 0,
        },
        {
          label: "红",
          value: 1,
        },
        {
          label: "蓝",
          value: 2,
        },
      ],
      form: {
        id: "",
        inx: "",
        signage: "",
        dimensionDTOList: [],
      },
      importIssueNo: "",
      importFile: "",
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      uploadMessage: "",
      isError: false,
      uploadVisible: false,
    };
  },
  computed: {
    actionUrl() {
      return process.env.VUE_APP_BASE_URL + "/quotaRecord/importQuotaRecord";
    },
    uploadData() {
      return { issueNo: this.importIssueNo };
    },
    formateColor() {
      return function (card) {
        const cardNum = card / 1;
        switch (cardNum) {
          case 0:
            return "green";
          case 1:
            return "red";
          default:
            return "blue";
        }
      };
    },
    formateCard() {
      return function (card) {
        const cardNum = card / 1;
        switch (cardNum) {
          case 0:
            return "绿";
          case 1:
            return "红";
          default:
            return "蓝";
        }
      };
    },
  },
  created() {
    this.getAreaList();
    this.getDateList();
    this.getTableData();
  },
  methods: {
    checkError() {
      this.$router.push({
        path: "/keyIndicatorsError",
      });
    },
    closeImport() {
      this.importVisible = false;
      this.importIssueNo = "";
      this.importFile = "";
    },
    confirmImport() {
      console.log("upload");
      if (this.importIssueNo === "") {
        return this.$message.error("请输入期号");
      }
      this.$refs.upload.submit();
      // if (this.importFile === "") {
      //   return this.$message.error("请上传导入文件");
      // }
      // this.$api
      //   .importQuotaRecord({
      //     file: this.importFile,
      //     issueNo: this.importIssueNo,
      //   })
      //   .then((res) => {});
    },
    beforeUpload(file) {
      const fileName = file.name;
      const reg = /(.xls|.xlsx)$/;
      if (!reg.test(fileName)) {
        this.$message.error("请上传.xls、.xlsx格式的文件");
        return false;
      }
    },
    successUp(res, file) {
      if (res.code === 200) {
        this.$message.success("上传成功");
        this.uploadMessage = res.data;
        if (res.data.indexOf("失败") != -1) {
          this.isError = true;
        } else {
          this.isError = false;
        }
        this.uploadVisible = true;
      } else {
        this.$message.error(res.msg);
      }
      this.importVisible = false;

      // console.log(res, "res");
      // console.log(file, "file");
      // // this.fileList.push({ id: file.uid, ...res });
      // this.importFile = res.url;
    },
    deleteFile() {
      this.importFile = "";
    },
    getAreaList() {
      const params = {
        _gp: "area",
        _mt: "list",
      };
      this.$api.commonApi(params).then((res) => {
        if (res.data.errno === 200) {
          this.areaList = res.data.data.map((item) => {
            return {
              label: item.areaName,
              value: item.areaId,
            };
          });
        } else {
          this.areaList = [];
        }
      });
    },
    getDateList() {
      const params = {
        _gp: "issue",
        _mt: "list",
      };
      this.$api.commonApi(params).then((res) => {
        if (res.data.errno === 200) {
          this.dateList = res.data.data.map((item) => {
            return {
              label: item,
              value: item,
            };
          });
        } else {
          this.dateList = [];
        }
      });
    },
    resetQuery() {
      this.queryParams = {
        area: "",
        date: "",
        indicator: "",
        current: 1,
        size: 10,
      };
      this.getTableData();
    },
    handleQuery() {
      this.queryParams.current = 1;
      this.getTableData();
    },
    // 每页显示数量变化
    sizeChange(size) {
      this.queryParams.size = size;
      this.queryParams.current = 1;
      this.getTableData();
    },

    // 当前页变化
    currentChange(current) {
      this.queryParams.current = current;
      this.getTableData();
    },
    getTableData() {
      this.tableLoading = true;
      const params = {
        quotaName: this.queryParams.indicator,
        issueNo: this.queryParams.date,
        areaId: this.queryParams.area,
        page: this.queryParams.current,
        size: this.queryParams.size,
      };
      this.$api.quotaRecordList(params).then((res) => {
        this.tableLoading = false;
        if (res.status === 200) {
          this.tableData = res.data.data.records || [];
          this.total = res.data.data.total;
        } else {
          this.tableData = [];
          this.total = 0;
        }
      });
    },
    handleEdit(row) {
      this.currentRow = row;
      this.form.dimensionDTOList = JSON.parse(
        JSON.stringify(row.dimensionDTOList)
      );
      this.form.id = row.id;
      this.form.signage = row.signage;
      this.visible = true;
    },
    // 进入展示导入错误结果展示
    onSuccess(record) {
      if (record === "success") return this.getTableData();
    },
    // 导入
    async importHandel() {
      // this.$refs.importFile.importHandel();
      this.importVisible = true;
    },
    // 下载模板
    exportHandel() {
      // const loading = this.$loading({
      //   lock: true,
      //   text: "请稍等。。。",
      //   spinner: "el-icon-loading",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      // this.$api.getModelUrl().then((res) => {
      //   if (res.data.errno == 200) {
      //     loading.close();
      //     window.open(res.data.url, "_blank");
      //   }
      // });
      window.open(
        "http://47.99.223.66:3392/gbzj/30fb79a678354ff5b1407338cb8484ff/辖区指标模板.xlsx",
        "_blank"
      );
    },
    close() {
      this.visible = false;
    },
    confirm() {
      const params = {
        id: this.form.id,
        position: this.form.inx,
        signage: this.form.signage,
        dimensionDTOList: this.form.dimensionDTOList,
      };
      this.$api.updateQuota(params).then((res) => {
        if (res.data.errno == 200) {
          this.$message.success("提交成功");
          this.resetQuery();
          this.visible = false;
        } else {
          this.$message.fail(res.data.errmsg);
        }
      });
    },
    toImport() {
      this.$router.push({
        path: "/keyIndicatorsImport",
      });
    },
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}
.edit_box .date {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}
.edit_box .date > div:first-child {
  color: #333;
  width: 100px;
  text-align: right;
}
.edit_box .quota_info {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}
.edit_box .quota_info .left > div:first-child,
.edit_box .quota_info .right > div:first-child {
  color: #333;
  width: 100px;
  text-align: right;
}
.edit_box .quota_info .left > div:last-child,
.edit_box .quota_info .right > div:last-child {
  width: 100px;
}
.edit_box .inx_box .left {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}
.edit_box .inx_box .left .tit {
  height: 28px;
  line-height: 28px;
  color: #333;
  width: 100px;
  text-align: right;
}
.edit_box .inx_box .left .old {
  width: 60px;
  height: 26px;
  line-height: 26px;
  text-align: center;
  background-color: #efefef;
  border: 1px solid #dcdcdc;
  margin-right: 20px;
}
.edit_box .inx_box .change {
  height: 28px;
  line-height: 28px;
  color: #2689fd;
  margin-right: 20px;
}
.edit_box >>> .el-input__inner {
  padding-right: 0;
}
.edit_box .inx_box .right {
  margin-left: 20px;
}
.edit_box .inx_box .right .tit {
  height: 28px;
  line-height: 28px;
  color: #333;
  margin-right: 20px;
}
.edit_box .inx_box .right .card {
  width: 50px;
  height: 26px;
  line-height: 26px;
  text-align: center;
  color: #fff;
  background-color: #4ca5f1;
  margin-right: 20px;
}
.edit_box .inx_box .right .card.green {
  background-color: #5bc55a;
}
.edit_box .inx_box .right .card.red {
  background-color: #e43c26;
}
.edit_box .dgree_box .tit {
  color: #333;
  width: 100px;
  height: 28px;
  line-height: 28px;
  text-align: right;
}
.edit_box .dgree_box .content .tit {
  width: 60px;
  height: 28px;
  line-height: 28px;
  font-size: 14px;
  margin-bottom: 20px;
  color: #666;
}
.blue {
  color: #4ca5f1;
}
.green {
  color: #5bc55a;
}
.red {
  color: #e43c26;
}
</style>